#!/bin/bash
#
# Copyright (C) 2024, 2025, Cyrus Li (e21920076@126.com). All rights reserved.
#

#
# Sync repos on gitee
#

function print { printf -- "$*\n"; }

function _isatty
{
	typeset -l isatty=$ISATTY
	[[ $isatty == "yes" ]] && return 0
	[[ $isatty ==  "no" ]] && return 1
	[[ -t 1 && -t 2 ]] && return 0 || return 1
}
function str2gray    { _isatty && print "\033[1;30m$@\033[m" || print "$@"; }
function str2red     { _isatty && print "\033[1;31m$@\033[m" || print "$@"; }
function str2green   { _isatty && print "\033[1;32m$@\033[m" || print "$@"; }
function str2yellow  { _isatty && print "\033[1;33m$@\033[m" || print "$@"; }
function str2blue    { _isatty && print "\033[1;34m$@\033[m" || print "$@"; }
function str2magenta { _isatty && print "\033[1;35m$@\033[m" || print "$@"; }
function str2cyan    { _isatty && print "\033[1;36m$@\033[m" || print "$@"; }
function str2white   { _isatty && print "\033[1;37m$@\033[m" || print "$@"; }

function run_git_cmd_prompt
{
	echo "$(id -un)@$(hostname):$(str2yellow $(pwd -P))\$ $(str2cyan $*)"
}

function run_git_cmd
{
	run_git_cmd_prompt "$@"
	eval "$*"
	typeset -i rc=$?
	echo
	return $rc
}

function _highlight
{
	typeset s=$(python3 -c "print('-' * 120)")
	echo
	str2blue "$s"
	echo
	sleep 2
}

function setup
{
	rm -rf $g_wsroot
	mkdir $g_wsroot
}

function cleanup
{
	cd /tmp
	rm -rf $g_wsroot
}

function clone
{
	typeset branch=${DW_MAIN_BRANCH:-"main"}

	cd $g_wsroot
	run_git_cmd git clone $g_origin_master

	cd $g_wsroot/$g_repo
	run_git_cmd git checkout $branch

	cd /tmp
}

function sync
{
	typeset branch=${UP_MAIN_BRANCH:-"main"}
	cd $g_wsroot/$g_repo
	run_git_cmd git remote -v
	run_git_cmd git remote add upstream $g_upstream_master
	run_git_cmd git remote -v
	run_git_cmd git fetch upstream $branch
	run_git_cmd git rebase upstream/$branch
	cd /tmp
}

function push
{
	typeset branch=${DW_MAIN_BRANCH:-"main"}
	cd $g_wsroot/$g_repo
	run_git_cmd_prompt git push origin $branch

	echo
	echo "TODO:"
	echo ">>> cd $g_wsroot/$g_repo"
	echo ">>> git push origin $branch"
	echo
}

repo=${1:-"anolis-community"}
case $repo in
"anolis-community"|"ac")
	g_origin_master=git@gitee.com:huanianlijing/anolis-community.git
	g_upstream_master=https://gitee.com/anolis/community.git
	g_repo=anolis-community
	g_wsroot=/tmp/foo-$g_repo
	export DW_MAIN_BRANCH="master"
	export UP_MAIN_BRANCH="master"
	;;
*)
	echo "Oops, unknown repo" >&2
	exit 1
	;;
esac

#trap "cleanup" EXIT
setup
_highlight
clone
_highlight
sync
_highlight
push
